package com.common.base.util;

import java.util.Locale;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.NoSuchMessageException;

public class ServiceHelper {
	
	private static ApplicationContext applicationContext;
	
	public static void setApplicationContext(ApplicationContext appContext) {
		applicationContext = appContext;
	}

	public static Object findBean(String beanId) {
		Object service = null;
		try {
			service = applicationContext.getBean(beanId);   

		} catch (NoSuchBeanDefinitionException ex) {
		//	throw new GlobalRuntimeException("no such bean for["+beanId+"]", ex);
		} catch (BeansException ex) {
		//	throw new GlobalRuntimeException("bean exception for["+beanId+"]", ex);
		}
		return service;
	}
//	
//	@SuppressWarnings(value="all")
//	public static Object findBeanOfType(Class clz) throws ServiceException {
//		if(logger.isDebugEnabled()) {
//			logger.debug("findBeanOfType="+ (clz==null?"Empty Class Name":clz.getName()));
//		}
//		if(clz==null) {
//			return null;
//		}
//		Object service = null;
//		try {
//			service = cacheAdmin.getFromCache(clz.getName());
//		} catch (NeedsRefreshException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		if(service==null) {
//			try {			
//				Map<String, Object> serviceMap = applicationContext.getBeansOfType(clz);
//				Iterator<String> beanNames=serviceMap.keySet().iterator();
//				while(beanNames.hasNext()) {
//					Object instance=serviceMap.get(beanNames.next());
//					if(instance.getClass().equals(clz)) {
//						service=instance;
//					} else if(AopUtils.isAopProxy(instance)) {
//						service=instance;
//						break;
//					}
//				}
//				cacheAdmin.putInCache(clz.getName(), service);
//			} catch (NoSuchBeanDefinitionException ex) {
//				throw new RuntimeException("no such bean for["+clz+"]", ex);
//			} catch (BeansException ex) {
//				throw new RuntimeException("bean exception for["+clz+"]", ex);
//			}	
//		}
//
//		return service;
//	}
//	

	public static String getMessage(String key, Object[] params, Locale locale) {
	    if(locale==null){
	        locale=new Locale("zh_CN");
	    }
	    String i18n="";
	    try {
            i18n=applicationContext.getMessage(key, params, locale);
        } catch (NoSuchMessageException e) {
        	e.printStackTrace();
        }
		return i18n;
	}

	   public static String getMessageDirect(String key, Object[] params, Locale locale) {
	        if(locale==null){
	            locale=new Locale("zh_CN");
	        }
	        return applicationContext.getMessage(key, params, locale);
	    }
	
}
